<template>
  <div class="stats-container">
    <performance-chart @trackEvent="trackEventHandler" v-if="type === 'task-trend'"></performance-chart>

    <div class="stats-row"> 
      <div class="stats-panel stats-panel-calendar" ref="calendar">
        <div class="stats-panel-head" :class="isCalendar?'stats-panel-head2':''">
          <div class="calendar-head">
            <button type="button" @click="adjustMonth(-1)">
              <i class="iconfont icon-xiangzuo"></i>
            </button>
            <span>{{currentMonth}}</span>
            <button type="button" @click="adjustMonth(1)">
              <i class="iconfont icon-xiangzuo-copy"></i>
            </button>
          </div>
        </div>
        <div class="calendar-options">
          <div class="charts-search-select mar-r-5">
            <span>OEM：</span>
            <el-select 
              :placeholder="$t('common.base.pleaseSelect')"
              v-model="OEM" 
              @change="chooseOEM"
              clearable
              class="stats-tags-select1">
              <el-option v-for="item in totalOEMList" :key="item" :label="item" :value="item"></el-option>
            </el-select>
          </div>
          <div class="charts-search-select flex-x flex-1">
            <span>{{$t('common.base.systemKeyword.customer')}}：</span>
            <biz-search-customer-select class="stats-tags-select2 flex-1" collapse :multiple="true" :value="customerIdList" @input="chooseCustomer" :remote-method="fetchCustomer" value-key="id" :collapsed="true" :placeholder="$t('report.common.allCustomer')"
            />
          </div>
        </div>
        <div class="stats-panel-body" >
          <div id="calendar"></div>
        </div>
        <div class="stats-panel-footer">
          <el-button type="primary" @click="openVacationDialog">{{ $t('report.performanceView.viewHoliday') }}</el-button>
        </div>
      </div>
      <div class="stats-panel" ref="dailyTable">
        <div class="stats-panel-head ">
          <span style="font-weight:600;font-size:16px;">{{dayStr}}</span>
          <el-radio-group v-model="tableType" size="mini" style="margin-left:20px;">
            <el-radio-button label="1">{{ $t('report.performanceView.planningBoard') }}</el-radio-button>
            <el-radio-button label="2">{{ $t('report.performanceView.workBoard') }}</el-radio-button>
          </el-radio-group>
        </div>
        <div class="stats-panel-body stats-daily-table-wrap">
          <div v-if="tableType=='1'">
            <div class="search-part">
              {{$t('common.fields.planNumber.displayName')}}：
              <el-input size="mini" v-model="planQuery.planNumber" style="width:180px;margin-right:10px;"></el-input>
              {{$t('common.customer.customerName')}}：
              <el-input size="mini" v-model="planQuery.customerName" style="width:180px;margin-right:10px;"></el-input>
              <el-button type="primary" @click="searchPlan">{{ $t('report.performanceView.query') }}</el-button>
              <el-button @click="resetPlan">{{$t('common.base.reset')}}</el-button>
              <el-button type="primary" @click="exportPlan">{{ $t('common.base.export') }}</el-button>
            </div>
            <el-table
              :data="planList"
              style="width: 100%"
              border
            >
              <el-table-column
                :label="$t('common.fields.planNumber.displayName')"
                min-width="120px"
                prop="planNumber"
              >
                <template slot-scope="{row}">
                  <span @click="openPlan(row)" class="href">{{row.planNumber}}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('task.edit.planName')" prop="planTaskName"></el-table-column>
              <el-table-column :label="$t('common.base.customer')" prop="customerName">
                <template slot-scope="{row}">
                  <span @click="openCustomer(row)" class="href">{{row.customerName}}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.task.flow.planStartTime')" prop="planTimeStart"></el-table-column>
              <el-table-column :label="$t('report.performanceView.endTime')" prop="planTimeEnd"></el-table-column>
              <el-table-column :label="$t('report.performanceView.planShaft')" prop="planWorkLoad"></el-table-column>
              <el-table-column :label="$t('report.performanceView.completeShaft')" prop="finishWorkLoad"></el-table-column>
              <el-table-column :label="$t('report.performanceView.completionProgress')" prop="finishRate"></el-table-column>
              <el-table-column :label="$t('report.calendar.planCount')" prop="planStaffCount"></el-table-column>
            </el-table>

            <el-pagination
              class="base-pagination"
              :background="true"
              layout="total, prev, pager,next,jumper"
              :total="planTotal"
              :page-size="planQuery.pageSize"
              :current-page="planQuery.pageNum"
              @current-change="jump"
            >
            </el-pagination>
          </div>

          <div v-if="tableType=='2'">
            <div class="search-part">
              {{$t('task.edit.planName')}}：
              <el-input size="mini" v-model="taskQuery.planTaskName" style="width:180px;margin-right:10px;"></el-input>
              {{$t('common.label.taskNo')}}：
              <el-input size="mini" v-model="taskQuery.taskNo" style="width:180px;margin-right:10px;"></el-input>
              {{$t('common.customer.customerName')}}：
              <el-input size="mini" v-model="taskQuery.windPlaceName" style="width:180px;margin-right:10px;"></el-input>
              <el-button type="primary" @click="searchTask">{{ $t('report.performanceView.query') }}</el-button>
              <el-button @click="resetTask">{{ $t('common.base.reset') }}</el-button>
              <el-button type="primary" @click="exportTask">{{ $t('common.base.export') }}</el-button>
            </div>
            <el-table
              :data="taskList"
              style="width: 100%"
              border
            >
              <el-table-column
                :label="$t('common.label.taskNo')"
                min-width="120px"
                prop="taskNo"
              >
                <template slot-scope="{row}">
                  <span @click="openTask(row)" class="href">{{row.taskNo}}</span>
                </template>
              </el-table-column>
              <el-table-column :label="$t('common.label.taskTemplate')" prop="templateName"></el-table-column>
              <el-table-column :label="$t('common.customer.customerName')" prop="customerName">
                <template slot-scope="{row}">
                  <span @click="openCustomer(row)" class="href">{{row.customerName}}</span>
                </template>
              </el-table-column>
              <el-table-column label="OEM" prop="customerOEM"></el-table-column>
              <el-table-column :label="$t('report.calendar.effectiveCount')" prop="effectiveCount"></el-table-column>
              <el-table-column :label="$t('report.calendar.invalidCount')" prop="invalidCount"></el-table-column>
              <el-table-column :label="$t('report.calendar.workCount')" prop="workingStaffCount"></el-table-column>
              <el-table-column :label="$t('report.calendar.officeCount')" prop="officeCount"></el-table-column>
              <el-table-column :label="$t('report.calendar.holidayCount')" prop="holidayWorkStaffCount"></el-table-column>
            </el-table>

            <el-pagination
              class="base-pagination"
              :background="true"
              layout="total, prev, pager,next,jumper"
              :total="taskTotal"
              :page-size="taskQuery.pageSize"
              :current-page="taskQuery.pageNum"
              @current-change="jump1"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <calendar-vacation-dialog ref="calendarVacation" />
  </div>
</template>

<script>
import { openAccurateTab } from '@src/util/platform';
import { formatDate, rangeOfMonth, dayTimeStart } from 'pub-bbx-utils';
import http from 'src/util/HttpUtil';       
import calendar from './calendar';
import moment from 'moment'
import { safeNewDate } from '@src/util/time';
import PerformanceChart from './PerformanceChart.vue';
import CalendarVacationDialog from './components/CalendarVacationDialog.vue';
import SampleTooltip from 'packages/SampleTooltip';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum'
import { getCustomerList } from '@src/api/CustomerApi'


export default {
  name: 'stats-performance-view',
  data() {
    return {
      msec: +new Date(),
      calendarStartTime: '',
      calendarEndTime: '',
      state: 'unfinished',
      day: '',
      type: '', // 判断入口
      isCalendar:true,
      totalOEMList:[],
      OEM:'',
      OEMFieldName:'',
      customerIdList:[],
      tableType:'1',
      planList:[], 
      planQuery:{
        pageNum:1,
        pageSize:8,
        planNumber:'',
        customerName:''
      },
      planTotal:0,
      taskList:[], 
      taskQuery:{
        pageNum:1,
        pageSize:8,
        taskNo:'',
        windPlaceName:''
      },
      taskTotal:0,
      dayStr: '',
    };
  },
  computed: {
    currentMonth() {
      return formatDate(this.msec, 'YYYY-MM');
    }
  },
  methods: {
    fetchCustomer(params){
      if (this.OEM) {
        params['conditions'] = [{property:this.OEMFieldName, value:this.OEM, key:null, operator:'eq'}]
      } else {
        params['conditions'] = []
      }
      return getCustomerList({...params})
    },
    chooseCustomer(value){
      this.customerIdList = value;
      let range = rangeOfMonth(this.msec);
      this.renderCalendar(range[0], range[1]);
    },
    adjustMonth(num){
      this.msec = moment(this.msec).add(num, 'month')
      let range = rangeOfMonth(this.msec);
      this.renderCalendar(range[0], range[1]);
    },  
    initCanlendar() {
      let range = rangeOfMonth(this.msec);
      calendar.init(document.getElementById('calendar'), this);
      calendar.chart.on('click', event => {
        let origin = event.data.origin;
        this.renderDailyTaskTable(+dayTimeStart(origin[0]));
      })

      this.renderCalendar(range[0], range[1]);
      this.renderDailyTaskTable(+dayTimeStart());
    },
    async renderCalendar(start, end){
      try {
        let instance = this.$loading.show(this.$refs.calendar);

        let data = await this.fetchCalendarData(start, end);
        let data1 = await this.fetchCalendarTotalData(start, end);
        instance.hide();
        calendar.render(start, end, data, data1);
      } catch (error) {
        console.log(error)
      }
    },
    fetchCalendarTotalData(start, end){
      let params = {
        'oemList': this.OEM ? [this.OEM] : [],
        'customerIdList': this.customerIdList.map(item=>{return item.id}),
        'month':`${formatDate(start, 'YYYY-MM')}` 
      }
      return http.post('/api/ssbreport/outside/staff/calendar/getMonthCount', params)
    },
    fetchCalendarData(start, end){
      let params = {
        'oemList': this.OEM ? [this.OEM] : [],
        'customerIdList':  this.customerIdList.map(item=>{return item.id}), 
        'month':`${formatDate(start, 'YYYY-MM')}` 
      }
      return http.post('/api/ssbreport/outside/staff/calendar/getEveryDayStaffCount', params)
    },
    async renderDailyTaskTable(day){
      try {
        this.day = day; // 时间戳转为年月日
        this.dayStr = formatDate(day, 'YYYY-MM')
        this.planQuery.pageNum = 1
        this.getPlanList()
        this.taskQuery.pageNum = 1
        this.getTaskList()
      } catch (error) {
        console.log(error)
      }
    },
    openTask(row){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `taskView_${ row.taskId}`, 
      //   title: `工单${row.taskNo}`,
      //   close: true, 
      //   url: `/task/view/${ row.taskId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageTaskView,
        key: row.taskId,
        titleKey: row.taskNo,
        fromId
      })
    },
    openPlan(row){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `task_edit_${row.planTaskId}`,
      //   title: '编辑计划任务',
      //   close: true,
      //   url: `/task/planTask/edit?id=${row.planTaskId}`,
      //   fromId,
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PagePlanTaskEdit,
        key: row.planTaskId,
        params: `id=${row.planTaskId}`,
        fromId
      })
      
    },
    openCustomer(row){
      let fromId = window.frameElement.getAttribute('id');
      // this.$platform.openTab({
      //   id: `customer_view_${row.customerId}`,
      //   title: '客户详情',
      //   close: true,
      //   url: `/customer/view/${row.customerId}`,
      //   fromId
      // });
      openAccurateTab({
        type: PageRoutesTypeEnum.PageCustomerView,
        key: row.customerId,
        fromId
      })
      
    },
    // TalkingData埋点事件
    trackEventHandler(type) {
      switch (type) {
      case 'chooseTeam':
        break;
      case 'chooseDate':
        break;
      default:
        break;
      }
    },
    mapTrackEventHandler(type) {
      switch (type) {
      case 'chooseTeam':
        break;
      default:
        break;
      }
    },
    chooseOEM(){
      this.customerIdList = []
      let range = rangeOfMonth(safeNewDate(this.msec));
      this.renderCalendar(range[0], range[1]);
    },
    async getOEMList(){
      return new Promise((resolve, reject)=>{
        http.get('/api/ssbreport/outside/staff/calendar/getCustomerOEMDatabase').then(res=>{
          resolve(res)
        })
      })
    },
    getPlanList(){
      let instance = this.$loading.show(this.$refs.dailyTable);
      this.planQuery.day = this.day
      http.post('/api/ssbreport/outside/staff/calendar/getPlanTaskPage', this.planQuery).then(res=>{
        if(res.code == 0){
          this.planList = res.data.list
          this.planTotal = res.data.total
        }
        
      }).finally(()=>{
        instance.hide()
      })
    },
    getTaskList(){
      let instance = this.$loading.show(this.$refs.dailyTable);
      this.taskQuery.day = this.day
      http.post('/api/ssbreport/outside/staff/calendar/getTaskPage', this.taskQuery).then(res=>{
        if(res.code == 0){
          this.taskList = res.data.list
          this.taskTotal = res.data.total
        }
      }).finally(()=>{
        instance.hide()
      })
    },
    searchPlan(){
      this.planQuery.pageNum = 1
      this.getPlanList() 
    },
    searchTask(){
      this.taskQuery.pageNum = 1
      this.getTaskList() 
    },
    // 计划任务翻页
    jump(val){
      this.planQuery.pageNum = val
      this.getPlanList() 
    },
    jump1(val){
      this.taskQuery.pageNum = val
      this.getTaskList() 
    },
    resetPlan(){
      this.planQuery = {
        pageNum:1,
        pageSize:8,
        planNumber:'',
        customerName:''
      }
      this.getPlanList()
    },
    resetTask(){
      this.taskQuery = {
        pageNum:1,
        pageSize:8,
        taskNo:'',
        windPlaceName:''
      }
      this.getTaskList()
    },
    exportPlan(){
      this.planQuery.day = this.day
      http.post('/api/ssbreport/outside/staff/calendar/exportPlanTask', this.taskQuery, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.$t('report.performanceView.scheduleTasks');
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      })
    },
    exportTask(){
      this.taskQuery.day = this.day
      http.post('/api/ssbreport/outside/staff/calendar/exportTask', this.taskQuery, true, {responseType: 'blob'}).then(blob=>{
        let link = document.createElement('a');
        let url = URL.createObjectURL(blob);
        link.download = this.$t('report.performanceView.scheduling');
        link.href = url;
        document.body.appendChild(link);
        link.click();
        setTimeout(() => {
          URL.revokeObjectURL(url);
          document.body.removeChild(link);
        }, 150);

      })
    },
    openVacationDialog() {
      this.$refs.calendarVacation.open()
    }
  },
  mounted() {
    this.type = window.location.href.split('type=')[1]
    this.getOEMList().then(res=>{
      if(res.code == 0){
        this.totalOEMList = res.data.database
        this.OEMFieldName = res.data.fieldName
        // this.OEM = res.data.database[0] || ''
        // 加载日历
        this.$nextTick(() => this.initCanlendar());
      }
    })
  },
  components: {
    [PerformanceChart.name]: PerformanceChart,
    [CalendarVacationDialog.name]: CalendarVacationDialog,
    [SampleTooltip.name]: SampleTooltip,
  }
};
</script>

<style lang="scss">
  .option-list{
    h3{
      font-size: 15px;
      font-weight: 600;
    }
  }
.stats-panel-calendar {
  flex-grow: 0.6 !important;
  min-width: 480px;
  
  .stats-panel-head{
    position: relative;
    // padding-left: 110px;

    h3{
      position: absolute;
      top: 6px;
      left: 6px;
    }

    .stats-tags-select1{
      width: 160px;
      display: inline-block;

      .biz-team-select-tag-text{
        max-width: 90px;
      }
    }
    .stats-tags-select2{
      display: none;
      width: 220px;
    }
  }
  .stats-panel-head2{
    // padding-left: 210px;
    .stats-panel-title{
      display: none;
    }
    .stats-tags-select1{
      position: absolute;
      left:0px;
    }
    .stats-tags-select2{
      display: inline-block;
      left: 170px;
      position: absolute;
      .base-select-container .base-select-main-content{
        line-height: 30px;
        display: flex;
        flex-wrap: wrap;
        border: 1px solid #e0e1e2;
        border-radius: 4px;
        padding: 0 10px;
        min-height: 32px;
        line-height: 30px
      }

    }
  }
  .stats-panel-footer{
    padding: 10px 0;
    text-align: center;
  }
}

.stats-container{
  .search-part{
    height:50px;
    display: flex;
    align-items: center;
    background:#eee;
    margin:8px;
    padding:6px;
    border-radius: 4px;
  }
  .href{
    color:$color-primary-light-6;
    cursor: pointer;
  }
}

  .calendar-options{
    // width:calc(100% - 160px);
    // position: absolute;
    // top: 3px;
    // left:160px;
    width: 100%;
    display: flex;
    padding:0 8px;
    margin-top:8px;
  }
.calendar-head{
  width: 140px;
  display: flex;
  flex-flow: row nowrap;
  span{
    display: block;
    width: 88px;
    font-size: 14px;
    text-align: center;
    color: #000;
    line-height: 26px;
  }

  button{
    background-color: transparent;
    border: none;
    width: 26px;
    line-height: 26px;
    text-align: center;
    padding: 0;
    border-radius: 2px;
    transition: all ease .15s;
    font-weight: 600;
    font-size: 14px;
    outline: none;

    &:hover{
      color: #337ab7;
      background-color: #f0f0f0;
    }
  }
}

.stats-plan-table{
  .base-table-head tr{
    background-color: #fafafa;

    th{
      line-height: 28px;
    }
  }
}

#calendar {
  margin: 0 auto;
  width: 480px;
  height: 500px;
}

#trend {
  height: 400px;
  margin: 0 auto;
}

.stats-daily-table-wrap {
  height: 495px;
}
.stats-daily-table-wrap {
  .base-table-cell {
    height: auto;
  }
}
.stats-panel-reference{
  position: absolute;
  top: 6px;
  left: 6px;
  display: inline-block;
  z-index:20;
}
.color-block{
  width:12px;
  height: 6px;
  display: inline-block;
  border-radius: 2px;
  margin-right: 4px;
  position: relative;
  top:-2px;
}
</style>
